<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
    <title>Netty-Websocket</title>
    <script type="text/javascript">
        //<![CDATA[

        // by zhengkai.blog.csdn.net
        var socket;
        if (!window.WebSocket) {
            window.WebSocket = window.MozWebSocket;
        }
        if (window.WebSocket) {
            var uid = [[${uid}]];
            socket = new WebSocket(`ws://localhost:11003/websocket?userId=${uid}`);
            socket.onmessage = function (event) {
                console.log('收到消息=' + event.data)
                var ta = document.getElementById('responseText');
                ta.value += event.data + "\r\n";
            };
            socket.onopen = function (event) {
                var ta = document.getElementById('responseText');
                ta.value = "Netty-WebSocket服务器。。。。。。连接  \r\n";
                var uid = document.getElementById("uid").value;
                // login(uid);
            };
            socket.onclose = function (event) {
                var ta = document.getElementById('responseText');
                ta.value = "Netty-WebSocket服务器。。。。。。关闭 \r\n";
            };
        } else {
            alert("您的浏览器不支持WebSocket协议！");
        }

        function send(fromId, msg, toId) {
            if (!window.WebSocket) {
                return;
            }
            if (socket.readyState == WebSocket.OPEN) {
                var jsonObject = {};
                jsonObject["fromId"] = fromId;
                jsonObject["msg"] = msg;
                jsonObject["toId"] = toId;

                socket.send(JSON.stringify(jsonObject));
            } else {
                alert("WebSocket 连接没有建立成功！");
            }
        }

        function login(fromId) {
            if (!window.WebSocket) {
                return;
            }
            if (socket.readyState == WebSocket.OPEN) {
                var jsonObject = JSON.parse("{}");
                jsonObject["login"] = fromId;
                socket.send(JSON.stringify(jsonObject));
            } else {
                alert("WebSocket 连接没有建立成功！");
            }
        }

        //]]>
    </script>
</head>
<body>
<form onSubmit="return false;">
    <label>ID</label><input id="uid" name="uid" th:value="${uid}" type="text"/><br/>
    <label>TEXT</label><input name="messageDTO" type="text" value="这里输入消息"/> <br/>
    <label>对方ID</label><input name="toUser" type="text" value="这里输入对方id"/> <br/>
    <br/> <input onClick="send(this.form.uid.value, this.form.messageDTO.value, this.form.toUser.value)" type="button"
                 value="发送ws消息"/>
    <hr color="black"/>
    <h3>服务端返回的应答消息</h3>
    <textarea id="responseText" style="width: 1024px;height: 300px;"></textarea>
</form>
</body>
</html>
